from rest_framework import serializers
from .models import *

# class DepartmentSerializer(serializers.Serializer):
#     id = serializers.IntegerField(label='ID',read_only=True)
#     name = serializers.CharField(label='部门名称', max_length=30)
#     def create(self, validated_data):
#         return Department.objects.create(**validated_data)
#
# class DutySerializer(serializers.Serializer):
#     id = serializers.IntegerField(label='ID',read_only=True)
#     name = serializers.CharField(label='职务名称', max_length=30)
#     def create(self, validated_data):
#         return Duty.objects.create(**validated_data)
#
# class StaffSerializer(serializers.Serializer):
#     SEX_CHOICE = (
#         (1, '男'),
#         (2, '女')
#     )
#     # 外键
#     #  必须readonly = True or queryset; read_only=True时，只序列化输出
#     # queryset时，只反序列化输入
#     department = serializers.PrimaryKeyRelatedField(read_only=True)
#     # department = serializers.PrimaryKkeyRelatedField(label="部门", queryset=Department.objects.all(),many=True)
#     duty = serializers.PrimaryKeyRelatedField(read_only=True)  #
#
#     name = serializers.CharField(max_length=30, label='姓名')
#     sex = serializers.IntegerField(label = '性别',default=1)
#     phone = serializers.CharField(max_length=11, label='手机号')
#     email = serializers.EmailField(max_length=60, label='邮箱')
#     census_register = serializers.CharField(max_length=200, label='户籍')
#     # picture = serializers.ImageField(label='员工照片')
class DepartmentModelSerializer(serializers.ModelSerializer):
    class Meta:
        model = Department  # 指定要序列化的模型类
        fields = '__all__'  # 指定要序列化的字段，__all__所有字段
class DutyModelSerializer(serializers.ModelSerializer):
    class Meta:
        model = Duty
        fields = "__all__"
class StaffModelSerializer(serializers.ModelSerializer):
    department_name = serializers.SerializerMethodField(read_only=True)
    duty_name = serializers.SerializerMethodField(read_only=True)
    class Meta:
        model = Staff
        fields = "__all__"
    def get_department_name(self, obj):
            return obj.department.name
    def get_duty_name(self, obj):
            return obj.duty.name


    # 外键， 指定queryset时，只用于反序列化输入
    # 		指定read_only=True，只用于序列化输出
    # department = serializers.PrimaryKeyRelatedField(label="部门", queryset=Department.objects.all(), many=True)
    # duty = serializers.PrimaryKeyRelatedField(label="职责", queryset=Duty.objects.all(), many=True)

    # class Meta:
    #     model = Staff
    #     fields = ("id", "name", "sex", "phone", "department", "duty")  # 外键要特殊处理
    #     read_only_fields = ("id",)
    #     write_only_fields = ("email",)